package android.slc.core.ui.fragment.preference;

import android.os.Bundle;
import android.slc.core.ui.delegate.CreateViewAuxiliaryWrapper;
import android.slc.core.ui.delegate.ISupportView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.XmlRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.PreferenceFragmentCompat;

/**
 * 基础视图代理
 * 单独拎出来作为一个类是为了降低耦合性，方便将此功能移植到此框架之外的框架中
 *
 * @author android.slc
 * @date 2021/2/5 15:07
 */
public class BasePreferenceViewDelegate implements DefaultLifecycleObserver {

    /**
     * 基于fragment的delegate
     */
    protected PreferenceFragmentCompat mFragment;

    /**
     * 视图信息桥接接口
     */
    protected IPreferenceSupportView mSupportView;

    /**
     * 唯一构造函数
     *
     * @param supportView
     */
    public BasePreferenceViewDelegate(IPreferenceSupportView supportView) {
        if (supportView instanceof PreferenceFragmentCompat) {
            this.mFragment = (PreferenceFragmentCompat) supportView;
            this.mSupportView = supportView;
            this.mFragment.getLifecycle().addObserver(this);
            return;
        }
        throw new IllegalStateException("supportView必须是PreferenceFragmentCompat");
    }

    /**
     * 初始化方法，接管{@link android.app.Activity}的初始化方法
     * 调用此方法后会回调{@link ISupportView#onBindViewBefore(),ISupportView#onBindView(),ISupportView#onBindViewLater()}方法
     *
     * @param savedInstanceState
     */
    public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
        this.mSupportView.onBindViewBefore();
        onInitView(savedInstanceState, rootKey);
        this.mSupportView.onBindViewLater();
    }

    /**
     * 初始化视图
     * 调用此方法后会回调{@link ISupportView#onBindView(Bundle)}方法
     */
    protected void onInitView(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
        mFragment.setPreferencesFromResource((int) mSupportView.setContentView(), rootKey);
        this.mSupportView.onBindView(savedInstanceState, rootKey);
    }


    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onDestroy(owner);
        if (this.mFragment != null) {
            this.mFragment.getLifecycle().removeObserver(this);
        }
        this.mFragment = null;
        this.mSupportView = null;
    }

}
